package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.dto.ArticleCommentDTO;
import com.sky.dto.ArticleSubmitDTO;
import com.sky.dto.ArticleTagsDTO;
import com.sky.mapper.ArticleMapper;
import com.sky.mapper.ArticleTagsMapper;
import com.sky.mapper.HomeMapper;
import com.sky.service.ArticleService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 贾晓晨
 * @version 1.0
 */
@Slf4j
@Service
public class ArticleServiceImp implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleTagsMapper articleTagsMapper;
    @Autowired
    private HomeMapper homeMapper;
    @Override
    public ArticleInfoVO getArticleDetail(String id) {
        return articleMapper.getArticleDetail(id);
    }

    @Override
    public void sendFirstComment(ArticleCommentDTO articleCommentDTO) {
        articleMapper.sendFirstComment(articleCommentDTO);
    }

    @Override
    public ArticleCommentsVO getCommentsByArticleUserId(String articleId) {
        // 1. 查询所有评论（单次查询）
        List<ArticleCommentDTO> allComments = articleMapper.selectCommentsByArticleUserId(articleId);

        // 2. 构建评论树
        return buildCommentTree(allComments, articleId);
    }

    @Override
    public void saveArticle(ArticleSubmitDTO articleSubmitDTO) {
        articleMapper.saveArticle(articleSubmitDTO);
    }

    @Override
    public void saveTag(List<String> tags) {
        // 先获取所有的tags
        List<ArticleTagsDTO> articleTagsDTO = articleTagsMapper.findAllTag();
        // 筛选出不存在的新标签
        List<String> newTags = tags.stream()
                .filter(tag -> !articleTagsDTO.contains(tag))
                .distinct() // 确保去重
                .collect(Collectors.toList());
        if (!newTags.isEmpty()) {
            // 批量插入新分类（数据库自动去重）
            articleTagsMapper.insertNewTag(newTags);
        }
    }

    @Override
    public List<ArticleTreeListVO> getTreeList() {
        // 1. 获取原始标签列表
        List<String> rawTagList = homeMapper.getTagList();
        if (CollectionUtils.isEmpty(rawTagList)) return Collections.emptyList();

        // 2. 标准化标签（去空格、转小写、去重）
        List<String> normalizedTagList = rawTagList.stream()
                .filter(StringUtils::isNotBlank)
                .map(t -> t.trim().toLowerCase())
                .distinct()
                .collect(Collectors.toList());

        // 3. 查询文章
        List<ArticleTagVO> articles = articleTagsMapper.findArticlesByTags(normalizedTagList);
        System.out.println(articles);
        if (CollectionUtils.isEmpty(articles)) return Collections.emptyList();
        // 4. 构建标签映射（标准化处理）
        Map<String, List<ArticleTagVO>> tagArticlesMap = new HashMap<>();
        articles.forEach(article ->
                        // System.out.println("article:" + article.getTags())
                Optional.ofNullable(article.getTags())
                        .orElse(Collections.emptyList())
                        .forEach(dbTag -> {
                            String normalizedDbTag = dbTag.trim().toLowerCase();
                            if (normalizedTagList.contains(normalizedDbTag)) {
                                tagArticlesMap.computeIfAbsent(normalizedDbTag, k -> new ArrayList<>())
                                        .add(article);
                            }
                        })
        );

        // 5. 构建树形结构（保留原始标签显示）
        return rawTagList.stream()
                .map(t -> t.trim().toLowerCase())
                .distinct()
                .map(tag -> {
                    List<ArticleTreeListVO.ArticleTreeVO> children =
                            tagArticlesMap.getOrDefault(tag, Collections.emptyList())
                                    .stream()
                                    .map(article -> ArticleTreeListVO.ArticleTreeVO.builder()
                                            .articleId(article.getArticleId())
                                            .title(article.getTitle())
                                            .build())
                                    .collect(Collectors.toList());

                    return ArticleTreeListVO.builder()
                            // .id(tag.hashCode())
                            .tag(tag)  // 显示标准化后的标签
                            // 如需显示原始标签，需额外维护映射关系
                            .children(children)
                            .build();
                })
                .filter(vo -> !vo.getChildren().isEmpty())
                .collect(Collectors.toList());
    }

    private ArticleCommentsVO buildCommentTree(List<ArticleCommentDTO> allComments, String articleId) {
        ArticleCommentsVO vo = new ArticleCommentsVO();
        vo.setArticleId(String.valueOf(articleId));

        // 创建映射：父评论ID → 子评论列表
        Map<Integer, List<ArticleCommentDTO>> childCommentMap = allComments.stream()
                .filter(c -> c.getHeadId() != null)
                .collect(Collectors.groupingBy(ArticleCommentDTO::getHeadId));

        // 处理顶级评论（headId为null）
        List<ArticleCommentsVO.CommentItem> commentItems = allComments.stream()
                .filter(c -> c.getHeadId() == null)
                .map(topComment -> {
                    ArticleCommentsVO.CommentItem item = new ArticleCommentsVO.CommentItem();
                    // 设置父评论信息
                    item.setId(topComment.getId());
                    item.setUserId(String.valueOf(topComment.getUserId()));
                    item.setNickName(topComment.getNickName());
                    item.setContent(topComment.getContent());
                    item.setContentImg(topComment.getContentImg());
                    item.setCreateTime(topComment.getCreateTime());
                    item.setAvatarUrl(topComment.getAvatarUrl());

                    // 处理子评论
                    List<ArticleChildCommentVo> childComments = childCommentMap.getOrDefault(topComment.getId(), Collections.emptyList())
                            .stream()
                            .map(child -> new ArticleChildCommentVo(
                                    child.getId(),
                                    String.valueOf(child.getUserId()),
                                    child.getNickName(),
                                    child.getAvatarUrl(),
                                    child.getContent(),
                                    child.getContentImg(),
                                    child.getParentName(),  // 被回复用户名称
                                    child.getCreateTime()
                            ))
                            .collect(Collectors.toList());

                    item.setChildComment(childComments);
                    return item;
                })
                .collect(Collectors.toList());

        vo.setCommentsList(commentItems);
        return vo;
    }

}
